package com.example.commonlib.commonutil;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.commonlib.constants.Constants;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Aiyou on 2017/8/9.
 */

public class MediaFileThumbUtils {
    /**
     * 获取本地视频的第一帧
     * @param filePath
     * @return
     */
    private static String getLocalVideoThumbnail(String filePath, String dstName){
        Bitmap bitmap = null;
        String absPath = "";
        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一的接口，用于从输入的媒体文件中取得帧和元数据；
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图
            MLog.i("file path:"+filePath);
            retriever.setDataSource(filePath);
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
            //存入SD卡
            String disPath = dstName+".jpg";

            absPath = BitmapUtil2.saveMyBitmap(Constants.VEDIO_IMG_ROOT,disPath,bitmap, Bitmap.CompressFormat.JPEG, 70);

        } catch (Exception e) {
            MLog.e("error:"+e.getMessage());
        } finally {
            if(bitmap != null)
            {
                bitmap.recycle();
            }
            retriever.release();
        }
        return absPath;
    }

    public static boolean isVideoThumbExist(String videoPath)
    {
        String md5Str = stringMD5(videoPath);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.VEDIO_IMG_ROOT + md5Str + ".jpg";
        File file = new File(thumPath);
        if(file.exists() && file.isFile())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static String getVideoThumbPath(String videoPath)
    {
        String md5Str = stringMD5(videoPath);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.VEDIO_IMG_ROOT + md5Str + ".jpg";
        return thumPath;
    }

    public static String buileVideoThumb(String videoPath)
    {
        String md5Str = stringMD5(videoPath);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.VEDIO_IMG_ROOT + md5Str + ".jpg";
        File file = new File(thumPath);
        if(file.exists() && file.isFile())
        {
            MLog.i("video thum alredy exist:"+file.getAbsolutePath());
            return file.getAbsolutePath();
        }

        String path = getLocalVideoThumbnail(videoPath, md5Str);
        return path;
    }

    public static String saveVideoThumbFileExist(Drawable drawable, String picUrl)
    {
        String md5Str = stringMD5(picUrl);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.VEDIO_IMG_ROOT + md5Str + ".jpg";
        File file = new File(thumPath);
        if(file.exists() && file.isFile())
        {
            MLog.i("video thum alredy exist:"+file.getAbsolutePath());
            return file.getAbsolutePath();
        }

        Bitmap bitmap = BitmapUtil2.drawableToBitmap(drawable);
        try {
            BitmapUtil2.saveMyBitmap(Constants.VEDIO_IMG_ROOT, md5Str + ".jpg", bitmap, Bitmap.CompressFormat.JPEG, 100);
        }
        catch (Exception ex)
        {
            MLog.e("save file 2 file failed:"+thumPath + "," + ex.getMessage());
        }
        finally {
            if(bitmap != null)
                bitmap.recycle();
        }
        return thumPath;
    }

    private static String stringMD5(String input)
    {
        try {
            // 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数组
            byte[] inputByteArray = input.getBytes();
            // inputByteArray是输入字符串转换得到的字节数组
            messageDigest.update(inputByteArray);
            // 转换并返回结果，也是字节数组，包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static String byteArrayToHex(byte[] byteArray) {
        // 首先初始化一个字符数组，用来存放每个16进制字符
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };

        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
        char[] resultCharArray =new char[byteArray.length * 2];
        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b& 0xf];
        }
        // 字符数组组合成字符串返回
        return new String(resultCharArray);
    }

    public static String getPicThumbFileExist(String url)
    {
        String md5Str = stringMD5(url);
        if(!TextUtils.isEmpty(md5Str))
        {
            String thumPath = Constants.SHARE_ROOT + md5Str + ".jpg";
            File file = new File(thumPath);
            if(file.exists() && file.isFile())
            {
                return file.getAbsolutePath();
            }
        }
        return "";
    }

    public static String savePicThumbFileExist(Drawable drawable, String picUrl)
    {
        String md5Str = stringMD5(picUrl);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.SHARE_ROOT + md5Str + ".jpg";
        File file = new File(thumPath);
        if(file.exists() && file.isFile())
        {
            MLog.i("pic thum alredy exist:"+file.getAbsolutePath());
            return file.getAbsolutePath();
        }

        Bitmap bitmap = BitmapUtil2.drawableToBitmap(drawable);
        try {
            BitmapUtil2.saveMyBitmap(Constants.SHARE_ROOT, md5Str + ".jpg", bitmap, Bitmap.CompressFormat.JPEG, 80);
        }
        catch (Exception ex)
        {
            MLog.e("save file 2 file failed:"+thumPath + "," + ex.getMessage());
        }
        finally {
            if(bitmap != null)
                bitmap.recycle();
        }
        return thumPath;
    }

    public final static int THUM_TYPE_CALL = 1;
    public final static int THUM_TYPE_LIVE = 2;
    public static String buildVideoCallShareThumb(Bitmap bitmap, int iType)
    {
        String fileNameKey = "";
        if(iType == THUM_TYPE_CALL)
        {
            fileNameKey = "aiyou_audio_call_thum";
        }
        else if(iType == THUM_TYPE_LIVE)
        {
            fileNameKey = "aiyou_media_live_thum";
        }
        String md5Str = stringMD5(fileNameKey);
        if(TextUtils.isEmpty(md5Str))
        {
            md5Str = System.currentTimeMillis()+"";
        }
        String thumPath = Constants.SHARE_ROOT + md5Str + ".jpg";
        File file = new File(thumPath);
        if(file.exists() && file.isFile())
        {
            MLog.i("audio call thum alredy exist:"+file.getAbsolutePath());
            return file.getAbsolutePath();
        }

        try {
            BitmapUtil2.saveMyBitmap(Constants.SHARE_ROOT, md5Str + ".jpg", bitmap, Bitmap.CompressFormat.JPEG, 70);
        }
        catch (Exception ex)
        {
            MLog.e("save file 2 file failed:"+thumPath + "," + ex.getMessage());
        }
        return thumPath;
    }




    public static final String M_TYPE_SCREEN_VIDEO = "4";
    public static final String M_TYPE_CAMERA_VIDEO = "5";
    public static final String M_TYPE_PICTURE = "6";

    static class glideLoadCb implements RequestListener<String, GlideDrawable>
    {
        String mUrl = "";
        String mMediaType = "";
        public glideLoadCb(String  url, String mType)
        {
            mUrl = url;
            mMediaType = mType;
        }

        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource)
        {
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model,
                                       Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource)
        {
            MLog.i(String.format("path:%s,%d*%d", model, resource.getIntrinsicWidth(), resource.getIntrinsicHeight()));
            if(TextUtils.equals(mMediaType, M_TYPE_SCREEN_VIDEO) || TextUtils.equals(mMediaType, M_TYPE_CAMERA_VIDEO))
            {
                if(!MediaFileThumbUtils.isVideoThumbExist(mUrl))
                {
                    String strThum = MediaFileThumbUtils.saveVideoThumbFileExist(resource, mUrl);
                    MLog.i("save video thum:" + mUrl+","+strThum);
                }
            }
            else if(TextUtils.equals(mMediaType, M_TYPE_PICTURE))
            {
                String thum = MediaFileThumbUtils.getPicThumbFileExist(mUrl);
                if(TextUtils.isEmpty(thum))
                {
                    String strThum = MediaFileThumbUtils.savePicThumbFileExist(resource, mUrl);
                    MLog.i("save pic thum:" + mUrl+","+strThum);
                }
            }
            return false;
        }
    }

    public static void loadThumb2Image(ImageView imageView, String orgUrl, String thumUrl, String fileType, int defPicRes)
    {
        if(TextUtils.equals(fileType, M_TYPE_SCREEN_VIDEO) || TextUtils.equals(fileType, M_TYPE_CAMERA_VIDEO))
        {
            if(MediaFileThumbUtils.isVideoThumbExist(orgUrl))
            {//存在本地缩略图
                String thum = MediaFileThumbUtils.getVideoThumbPath(orgUrl);
                Glide.with(App.INSTANCE)
                        .load(thum)
                        .placeholder(defPicRes)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .thumbnail(1.0f)
                        .dontAnimate()
                        .into(imageView);
            }
            else
            {//不存在本地缩略图
                Glide.with(App.INSTANCE)
                        .load(thumUrl)
                        .listener(new glideLoadCb(orgUrl, fileType))
                        .placeholder(defPicRes)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .thumbnail(0.8f)
                        .dontAnimate()
                        .into(imageView);
            }
        }
        else if(TextUtils.equals(fileType, M_TYPE_PICTURE))
        {
            String thum = MediaFileThumbUtils.getPicThumbFileExist(orgUrl);
            if(!TextUtils.isEmpty(thum))
            {//存在本地缩略图
                Glide.with(App.INSTANCE)
                        .load(thum)
                        .placeholder(defPicRes)
                        .thumbnail(1.0f)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .dontAnimate()
                        .into(imageView);
            }
            else
            {
                Glide.with(App.INSTANCE)
                        .load(orgUrl)
                        .listener(new glideLoadCb(orgUrl, fileType))
                        .placeholder(defPicRes)
                        .thumbnail(0.8f)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .dontAnimate()
                        .into(imageView);
            }
        }
    }
}
